package com.j1ay.forum.service.impl;

import com.alibaba.fastjson.JSON;
import com.j1ay.forum.model.pojo.po.User;
import com.j1ay.forum.service.LoginService;
import com.j1ay.forum.service.UserService;
import com.j1ay.forum.utils.JWTUtils;
import com.j1ay.forum.model.pojo.vo.ErrorCode;
import com.j1ay.forum.model.dto.params.RegisterParams;
import com.j1ay.forum.model.pojo.vo.Result;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author J1ay
 * @Date 2021/12/15 13:42
 * @Description
 */

@Service
@Transactional
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    // 加密盐值
   // private static final String slat = "J1ay@2021";


    /**
     * 验证token是否合法
     * @param token
     * @return
     */
    @Override
    public User checkToken(String token) {
        if (StringUtils.isBlank(token)) {
            return null;
        }
        System.out.println(token);
        token = token.replace("Bearer ", "");
        System.out.println(token);
        Map<String, Object> stringObjectMap = JWTUtils.checkToken(token);
        if (null == stringObjectMap) {
            return null;
        }
        String userJson = redisTemplate.opsForValue().get("TOKEN_" + token);
        if (StringUtils.isBlank(userJson)) {
            return null;
        }
        User user = JSON.parseObject(userJson, User.class);

        return user;
    }

    /**
     * 销毁token 用户退出
     * @param token
     * @return
     */
    @Override
    public Result logout(String token) {
        token = token.replace("Bearer ", "");
        redisTemplate.delete("TOKEN_" + token);
        return Result.success(null);
    }
}
